package com.example.sy_2.servlet;

// CountServlet.java
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;
import java.io.IOException;

@WebServlet("/count")
public class CountServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        // 给访问次数设置初始值 0，并存入到 ServletContext 中
        int count = 0;
        ServletContext context = getServletContext();
        context.setAttribute("visitCount", count);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 从 ServletContext 中取出当前的访问次数
        ServletContext context = getServletContext();
        int count = (int) context.getAttribute("visitCount");

        // 访问次数加 1
        count += 1;

        // 将新的访问次数存入到 ServletContext 中
        context.setAttribute("visitCount", count);

        // 设置响应内容类型，并输出欢迎信息和访问次数
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("<h1>欢迎光临本网站! 这是您第 " + count + " 次访问</h1>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 调用 doGet 方法处理 POST 请求
        doGet(request, response);
    }
}
